<?php 
class Ad extends Object
{
	public $TypeId;
	public $TypeTitle;
	public $CatId;
	public $CatTitle;
	public $BrandId;
	public $BrandTitle;
	public $ModId;
	public $ModTitle;
	public $UserId;
	public $UserImage;
	public $UserImageObject;
	public $OrderId;
	public $ProductId;
	public $AdQuotas;
	public $UseCredits;
	
	public $IsBuying;
	public $IsRent;
	public $IsNew;
	public $IsCompleted;
	public $IsValid;
	
	public $Title;
	public $TitleEn;
	public $MetaTitle;
	public $Description;
	public $DescriptionEn;
	public $ProductLink;
	public $ProductLink2;
	public $ProductLinkTxt;
	public $ProductLinkTxt2;
	public $Summary;
	public $PriceDisplay;
	public $PriceCurrency;
	public $PriceLocal;
	public $PriceGlobal;
	
	public $Model;
	public $Year;
	public $LengthUsed;
	public $Weight;
	public $Power;
	public $Volume;
	public $SerialNo;
	
	public $ContactEmail;
	public $ContactName;
	public $ContactCompany;
	public $ContactWeb;
	public $ContactMob;
	public $ContactPhone;
	
	public $LocationCoords;
	public $LocationAddress;
	public $LocationZip;
	public $LocationCity;
	public $LocationCountry;
	public $LocationCountryName;
	public $CountryPartId;
	public $CountryPartTitle;
	
	public $SearchKeys;
	public $Priority;
	public $DateCreated;
	public $DateModified;
	public $DatePaid;
	public $DateActiveStart;
	public $DateActiveEnd;
	public $Image;
	public $ImageId;
	public $Images;
	public $Files;
	public $Active;
	public $Archived;
	public $Deleted;
	public $GalleryDisplay;
	
	public $RemoteId;
	public $RemoteUrl;
	
	public $ViewsList;
	public $ViewsDetail;
	public $ViewsGallery;
	
	public $PartnerStatus;
	
	public function Ad($values = Array())
	{ 
		self::setDataTable('am_ads');
		self::setImagesTable('am_ad_images');
		self::setFilesTable('am_ad_files');
		self::setItemLoaded('images', false);
		if(count($values) > 0)
		{ self::setValues($values); }
	}
	
	public function __toString()
	{
		$out .= self::getTypeTitle().', ';
		$out .= self::getCatTitle().', ';
		$out .= self::getBrandTitle().', ';
		$out .= self::getId().', ';
		$out .= self::getTitle().', ';
		$out .= self::getTitleEn().', ';
		return $out;
	}
	
	public function makeTitle($forceNew=0)
	{
		if(($this->Title != '') && ($forceNew == 0))
		{ return $this->Title; }
		else
		{
			if(self::getDisplayIsNew())
			{
				global $txt;
				if(self::getIsNew())
				{ $this->Title = ucfirst($txt->getWord('new')).' '; }
				else
				{ $this->Title = ucfirst($txt->getWord('used')).' '; }
			}
			
			if(self::getBrandTitle() != '')
			{ $this->Title .= self::getBrandTitle(); }
			if((self::getDisplayModel() > 0) && (self::getModel() != ''))
			{ $this->Title .= ' - '.self::getModel(); }
			if((self::getDisplayYear() > 0) && (self::getYear() > 0))
			{ $this->Title .= ' - '.self::getYear(); }
		}
	}
	
	public function getMakeTitle()
	{
		if(self::getTitle() != '')
		{ return ucfirst(self::getTitle()); }
		if(self::getTitleEn() != '')
		{ return ucfirst(self::getTitleEn()); }
	}
	
	public function getMetaTitle()
	{
		if($this->MetaTitle == '')
		{ self::loadMetaTitle(); }
		return $this->MetaTitle;
	}
	
	public function loadMetaTitle()
	{
		switch(self::getAdTypeObject())
		{
			case 'AdVehicle':
			case 'AdVehicleLight':
				if(self::getDisplayIsNew() > 0)
				{
					global $txt;
					if(substr_count(self::getTitle(), ucfirst($txt->getWord('used'))) == 0)
					{
						if(self::getIsNew())
						{ $this->MetaTitle = ucfirst($txt->getWord('new')); }
						else
						{ $this->MetaTitle = ucfirst($txt->getWord('used')); }
						//##self::getAdTypeObject()
						//AdEmployment
					}
				}
			break;
		}
		
		
		$this->MetaTitle .= ' '.self::getTitle();
		
		if(self::getTitle() == self::getBrandTitle())
		{
			if((self::getDisplayModel() > 0) && (self::getModel() != ''))
			{ $this->MetaTitle .= ' - '.self::getModel(); }
			if((self::getDisplayYear() > 0) && (self::getYear() > 0))
			{ $this->MetaTitle .= ' - '.self::getYear(); }
		}
		
		global $katana;
		
		$katana->addHeaderItem('<meta itemprop="name" content="'.self::getTitle().'" >');
		$katana->addHeaderItem('<meta itemprop="description" content="'.self::getSummary().'" >');
		
		$katana->addHeaderItem('<meta property="og:type" content="product" >');
		$katana->addHeaderItem('<meta property="og:title" content="'.self::getTitle().'" >');
		$katana->addHeaderItem('<meta property="og:description" content="'.self::getSummary().'" >');
		if(self::getImage() != '')
		{ 
			$katana->addHeaderItem('<meta itemprop="image" content="'.self::getImage()->getLink().'" >');	
			$katana->addHeaderItem('<meta property="og:image" content="'.self::getImage()->getLink().'" >'); 
		}
		$katana->addHeaderItem('<meta property="og:url" content="'.self::getLink().'" >');
		$katana->addHeaderItem('<link rel="canonical" href="'.self::getLink().'" />');
	}
	
	public function getLink()
	{ return SITE_URL.'ad/'.self::getId().'/'; }
	
	public function getContactWeb()
	{
		if($this->ContactWeb != '')
		{
			if(!(substr_count($this->ContactWeb, 'http://') > 0))
			{ $this->ContactWeb = 'http://'.$this->ContactWeb; }
			return $this->ContactWeb;
		}
		else
		{ return $this->ContactWeb; }
	}
	
	public function getSummary()
	{
		self::loadSummary();
		return $this->Summary;
	}
	
	public function loadSummary($wrapper = 0)
	{
		if((!self::getItemLoaded('Summary')))
		{
			global $txt;
			global $katana;
			global $adc;
			
			if((self::getDisplayYear() > 0) && (self::getYear() > 0))
			{ 
				if($katana->getList() != '') 
				{ $this->Summary .= '<span class="year">'; }
				$this->Summary .= ucfirst($txt->getWord('year_production')).':&nbsp;'.self::getYear().', ';
				if($katana->getList() != '')
				{ $this->Summary .= '</span>'; }
			}
			
			if((self::getDisplayBrand() > 0) && (self::getBrandTitle() != ''))
			{ $this->Summary .= self::getBrandTitle().' '; }
			
			if((self::getDisplayModel() > 0) && ((self::getModTitle() != '') || (self::getModel() != '')))
			{ $this->Summary .= self::getModTitle().self::getModel(); }
			
			if(self::getLengthUsed() > 0)
			{ 
				switch(self::getAdTypeObject())
				{
					case 'AdVehicle':
						switch(self::getTypeId())
						{
							case 1:
							case 3:
								$this->Summary .= ', ';
								if($katana->getList() != '')
								{ $this->Summary .= '<span class="used">'; }
								$this->Summary .= ucfirst($txt->getWord('work_hours')).':&nbsp;'.number_format(self::getLengthUsed(),0,'',' ');
								if($katana->getList() != '')
								{ $this->Summary .= '</span>'; }
							break;
							case 2:
								$this->Summary .= ', ';
								if($katana->getList() != '')
								{ $this->Summary .= '<span class="used">'; }
								$this->Summary .= ucfirst($txt->getWord('mileage')).':&nbsp;'.number_format(self::getLengthUsed(),0,'',' ').'&nbsp;km';
								if($katana->getList() != '')
								{ $this->Summary .= '</span>'; }
							break;
						}
					break;
					case 'AdVehicleLight':
					default:
						$this->Summary .= ', ';
						if($katana->getList() != '')
						{ $this->Summary .= '<span class="used">'; }
						$this->Summary .= ucfirst($txt->getWord('mileage')).':&nbsp;'.number_format(self::getLengthUsed(),0,'',' ').'&nbsp;km';
						if($katana->getList() != '')
						{ $this->Summary .= '</span>'; }
					break;
				}
			}
			
			if((self::getPriceDisplay() > 0) && (self::getUsePrice() > 0) && (self::getPriceGlobal() > 0))
			{ 
				if($this->Summary != '')
				{ $this->Summary .= ', '; }
				if($katana->getList() != '')
				{ $this->Summary .= '<span class="price">'; }
				
				if(self::getIsBuying() > 0) 
				{ $this->Summary .= ucfirst($txt->getWord('max')); }
				
				$this->Summary .= ucfirst($txt->getWord('price')).': ';
				if(($adc->getSetting('LocalCurrencyDisplay') > 0) && (self::getPriceLocal() > 0))
				{ $this->Summary .= self::getPriceLocalTxt(0).' '.self::getPriceCurrency(); }
				else
				{ $this->Summary .= self::getPriceGlobalTxt(0).' '.$adc->getSetting('GlobalCurrency'); }
				if($katana->getList() != '')
				{ $this->Summary .= '</span>'; }
			}
			
			if(($this->Summary != '') && ($katana->getList() != ''))
			{ $this->Summary = '<div class="summary">'.$this->Summary.'</div>'; }
				
			self::setItemLoaded('Summary', true);
		}
	}
	
	public function loadMetaData()
	{
		global $katana;
		
		$katana->setDetailView(true);
		$katana->setMetaTitle(self::getMetaTitle());
		$katana->addAfterMetaTitle(self::getBrandTitle()); //Seo friendly
		$katana->addAfterMetaTitle(self::getCatTitle()); //Seo friendly
		$katana->addAfterMetaTitle(self::getTypeTitle()); //Seo friendly
		$katana->addAfterMetaTitle(ucfirst(self::getIsBuyingText()));
		$katana->addAfterMetaTitle($katana->getTitle());
		
		$katana->setMetaData($katana->getTitle());
		$katana->addBeforeMetaData(self::getIsBuyingText());
		$katana->addBeforeMetaData(self::getTypeTitle());
		$katana->addBeforeMetaData(self::getCatTitle());
		$katana->addBeforeMetaData(self::getTypeTitle());
		$katana->addBeforeMetaData(self::getBrandTitle());
		$katana->addBeforeMetaData(self::getMetaTitle());
		
		$katana->setMetaKey($katana->getTitle());
		$katana->addBeforeMetaKey(self::getIsBuyingText());
		$katana->addBeforeMetaKey(self::getTypeTitle());
		$katana->addBeforeMetaKey(self::getCatTitle());
		$katana->addBeforeMetaKey(self::getTypeTitle());
		$katana->addBeforeMetaKey(self::getBrandTitle());
		$katana->addBeforeMetaKey(self::getMetaTitle());
	}
	
	
	public function getTypeId() { return intval($this->TypeId); }
	public function getCatId() { return intval($this->CatId); }
	public function getBrandId() { return intval($this->BrandId); }
	public function getModId() { return intval($this->ModId); }
	public function getUserId() { return intval($this->UserId); }
	public function getOrderId() { return intval($this->OrderId); }
	public function getProductId() { return intval($this->ProductId); }
	public function getIsBuying() { return intval($this->IsBuying); }
	public function getIsBuyingText() 
	{ 
		global $txt;
		if($this->IsBuying > 0)
		{ 
			if(self::getIsRent() > 0)
			{ return $txt->getWord('To_rent'); }
			else
			{
				if($txt->getWord('buying_'.$this->TypeId) != 'buying_'.$this->TypeId)
				{ return $txt->getWord('buying_'.$this->TypeId);  }
				else
				{ return $txt->getWord('buying'); }
			}
		}
		else
		{ 
			if(self::getIsRent() > 0)
			{ return $txt->getWord('for_rent'); }
			else
			{
				if($txt->getWord('selling_'.$this->TypeId) != 'selling_'.$this->TypeId)
				{ return $txt->getWord('selling_'.$this->TypeId);  }
				else
				{ return $txt->getWord('selling'); }
			}
		}
	}
	public function getIsBoughtText()
	{ 
		global $txt;
		if($this->IsBuying > 0)
		{ 
			if(self::getIsRent() > 0)
			{ return $txt->getWord('rented_in'); }
			else
			{
				if($txt->getWord('bought_'.$this->TypeId) != 'bought_'.$this->TypeId)
				{ return $txt->getWord('bought_'.$this->TypeId);  }
				else
				{ return $txt->getWord('bought'); }
			}
		}
		else
		{ 
			if(self::getIsRent() > 0)
			{ return $txt->getWord('rented_out'); }
			else
			{
				if($txt->getWord('sold_'.$this->TypeId) != 'sold_'.$this->TypeId)
				{ return $txt->getWord('sold_'.$this->TypeId);  }
				else
				{ return $txt->getWord('sold'); }
			}
		}
	}
	public function getIsRent() { return intval($this->IsRent); }
	public function getIsNew() { return intval($this->IsNew); }
	public function getIsCompleted() { return intval($this->IsCompleted); }
	public function getIsValid() { return intval($this->IsValid); }

	public function getPriceDisplay() { return intval($this->PriceDisplay); }
	public function getPriceLocal($round = 0, $format=true) 
	{ 
		if(is_numeric($this->PriceLocal))
		{
			if($round > 0)
			{ 
				if($format)
				{ return number_format(round($this->PriceLocal,$round),2,'.',''); }
				else
				{ return round($this->PriceLocal,$round); }
			}
			else
			{
				if($format)
				{ return number_format($this->PriceLocal,2,'.',''); }
				else
				{ return $this->PriceLocal; }
			}
		}
		else
		{ 
			self::setPriceLocal(0);
			return $this->PriceLocal;
		}
	}
	public function getPriceGlobal($round = 0, $format=true) 
	{ 
		if(is_numeric($this->PriceGlobal))
		{
			if($round > 0)
			{ 
				if($format)
				{ return number_format(round($this->PriceGlobal,$round),2,'.',''); }
				else
				{ return round($this->PriceGlobal,$round); }
			}
			else
			{
				if($format)
				{ return number_format($this->PriceGlobal,2,'.',''); }
				else
				{ return $this->PriceGlobal; }
			}
		}
		else
		{ 
			self::setPriceGlobal(0);
			return $this->PriceGlobal;
		}
	}
	public function getPriceLocalTxt($round = 0) 
	{ 
		if(is_numeric($this->PriceLocal))
		{
			if($round > 0)
			{ return number_format(round($this->PriceLocal,$round),2,',',' '); }
			else
			{ return number_format(round($this->PriceLocal,$round),$round,',',' '); }
		}
	}
	public function getPriceGlobalTxt($round = 0) 
	{ 
		if(is_numeric($this->PriceGlobal))
		{
			if($round > 0)
			{ return number_format(round($this->PriceGlobal,$round),2,',',' '); }
			else
			{ return number_format(round($this->PriceGlobal,$round),$round,',',' '); }
		}
	}
	public function getYear() { return intval($this->Year); }
	public function getLengthUsed() { return intval($this->LengthUsed); }
	public function getWeight() { return intval($this->Weight); }
	public function getPower() { return intval($this->Power); }
	public function getVolume() { return intval($this->Volume); }
	public function getSearchKeys() { return $this->SearchKeys; }
	
	public function getCountryPartId() { return intval($this->CountryPartId); }
	public function getPriority() { return intval($this->Priority); }
	public function getDateCreated($format = '')
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateCreated, $format); }
		else
		{ return $this->DateCreated; }
	}
	public function getDateModified($format = '') 
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateModified, $format); }
		else
		{ return $this->DateModified; }
	}
	public function getDatePaid() { return $this->DatePaid; }
	public function getDateActiveStart($format = '') 
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateActiveStart, $format); }
		else
		{ return $this->DateActiveStart; }
	}
	public function getDateActiveEnd($format = '')
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateActiveEnd, $format); }
		else
		{ return $this->DateActiveEnd; } 
	}
	public function getArchived() { return intval($this->Archived); }
	public function getDeleted() { return intval($this->Deleted); }
	public function getGalleryDisplay() { return intval($this->GalleryDisplay); }
	public function getRemoteId() { return intval($this->RemoteId); }
	
	public function getViewsList() { return intval($this->ViewsList); }
	public function getViewsDetail() { return intval($this->ViewsDetail); }
	public function getViewsGallery() { return intval($this->ViewsGallery); }
	public function getAdQuotas() { return intval($this->AdQuotas); }
	public function getUseCredits() { return intval($this->UseCredits); }
	public function getPartnerStatus() { return intval($this->PartnerStatus); }
	
	public function getDisplayPrice() { return self::getUsePrice(); }
	public function getDisplayBrand() { return self::getUseBrand(); }
	public function getDisplayYear() { return self::getUseYear(); }
	public function getDisplayModel() { return self::getUseModel(); }
	public function getDisplayIsNew() { return self::getUseIsNew(); }
	
	public function getUsePrice() { return 1; }
	public function getUseBrand() { return 1; }
	public function getUseYear() { return 1; }
	public function getUseModel() { return 1; }
	public function getUseIsNew() { return 1; }
	
	public function getIsPaid()
	{ 
		if(self::getProductId() > 0)
		{
			if(self::getDatePaid() != '0000-00-00 00:00:00')
			{ return 1; }
			else
			{ return 0; }
		}
		else
		{ return 1; }
	}
	
	public function getIsDeletable()
	{ 
		$deletable = 0;
		if(self::getActive() == 0) //Inactive New Ads
		{
			if(self::getProductId() > 0)
			{
				if(self::getDatePaid() == '0000-00-00 00:00:00')
				{ $deletable = 1; }
			}
			else
			{ $deletable = 1; }
			if(self::getAdQuotas() != 0)
			{ $deletable = 0; }
		}
		else
		{ 
			global $adc;
			if($adc->getSetting('UserAdDelete') > 0)
			{ $deletable = 1; }
		}
		
		return $deletable;
	}
	
	public function getImage() 
	{
		self::loadImages();
		return $this->Image; 
	}
	public function getImageId() { return intval($this->ImageId); }
	public function getImages() 
	{
		self::loadImages();
		return $this->Images; 
	}
	public function getFiles() 
	{
		self::loadFiles();
		return $this->Files; 
	}
	
	public function setTypeId($val) { $this->TypeId=intval($val); }
	public function setCatId($val) { $this->CatId=intval($val); }
	public function setBrandId($val) { $this->BrandId=intval($val); }
	public function setModId($val) { $this->ModId=intval($val); }
	public function setUserId($val) { $this->UserId=intval($val); }
	public function setOrderId($val) { $this->OrderId=intval($val); }
	public function setProductId($val) { $this->ProductId=intval($val); }
	public function setIsBuying($val) { $this->IsBuying=intval($val); }
	public function setIsRent($val) { $this->IsRent=intval($val); }
	public function setIsNew($val) { $this->IsNew=intval($val); }
	public function setIsCompleted($val) { $this->IsCompleted=intval($val); }
	public function setIsValid($val) { $this->IsValid=intval($val); }
	public function setPriceDisplay($val) { $this->PriceDisplay=intval($val); }
	public function setPriceLocal($val) { $this->PriceLocal=$val; }
	public function setPriceGlobal($val) { $this->PriceGlobal=$val; }
	public function setYear($val) { $this->Year=intval($val); }
	public function setLengthUsed($val) { $this->LengthUsed=intval($val); }
	public function setWeight($val) { $this->Weight=intval($val); }
	public function setPower($val) { $this->Power=intval($val); }
	public function setVolume($val) { $this->Volume=intval($val); }
	public function setSearchKeys($val) { $this->SearchKeys=$val; }
	public function setPriority($val) { $this->Priority=intval($val); }
	public function setCountryPartId($val) { return intval($val); }
	public function setArchived($val) { $this->Archived=intval($val); }
	public function setDeleted($val) { $this->Deleted=intval($val); }
	public function setGalleryDisplay($val) { $this->GalleryDisplay=intval($val); }
	public function setRemoteId($val) { $this->RemoteId=intval($val); }
	public function setViewsList($val) { $this->ViewsList=intval($val); }
	public function setViewsDetail($val) { $this->ViewsDetail=intval($val); }
	public function setViewsGallery($val) { $this->ViewsGallery=intval($val); }
	public function setAdQuotas($val) { $this->AdQuotas=intval($val); }
	public function setUseCredits($val) { $this->UseCredits=intval($val); }
	public function setImageId($val) { $this->ImageId=intval($val); }
	
	function Publish()
	{
		global $user;
		global $katana;
		global $shop;
		global $adc;
		if((self::getIsPaid() > 0) && ((self::getUserId() == $user->getId()) || (defined('RUN_IMPORT'))))
		{
			$info['sucess'] = true;
			if(self::getActive() == 0)
			{
				if(self::getOrderId() > 0)
				{
					$shop->setCurrentOrderId(self::getOrderId());
					if(is_object($shop->getCurrentOrder()))
					{
						if($shop->CurrentOrder->getDateDelivered() == '0000-00-00 00:00:00')
						{ $info = $shop->changeOrderDeliveryStatus($shop->getCurrentOrderId(), 2); }
					}
				}
			} 
			if($info['sucess'])
			{
				$currentDAS = date('Y-m-d H:i:s');
				if(strtotime(self::getDateActiveStart()) > time())
				{ $currentDAS = self::getDateActiveStart(); }
				
				self::setDateActiveStart($currentDAS);
				self::setDateCreated($currentDAS);
				//self::setDateModified(date('Y-m-d H:i:s'));
				//mktime(hour,minute,second,month,day,year,is_dst) 
				
				$dateActiveEnd  = strtotime($currentDAS);
				$dateActiveEnd += (60*60*24*intval($adc->getSetting('AdsMaxAge'))); //Normally 360days
				if(self::getPartnerStatus() > 2)
				{ $dateActiveEnd += (60*60*24*(intval($adc->getSetting('AdsMaxAge'))+40)); }  //add 40 days
				
				self::setDateActiveEnd(date('Y-m-d H:i:s', $dateActiveEnd));
				self::setActive(1);
				self::setArchived(0);
				self::setViewsGallery(0);
				self::setIsCompleted(0);
				self::setDataChanged(1);
				self::updateAd();
				$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/ad/activate/success']);");
			}
		}
	}
	
	function delete()
	{
		global $katana;
		global $user;
		$error = false;
		if((self::getUserId() == $user->getId()) || ($user->getLevel() > 4))
		{
			$this->setDeleted(1);
			$this->setDataChanged(1);
			$this->deleteImages();
			$this->update();
			$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/ad/delete/success']);");
			return true;
		}
		else
		{ 
			$error['txt'] = 'could_not_delete';
			$error['description'] = 'no_access';
			return $error;
		}
	}
	function archive()
	{
		global $katana;
		global $user;
		if(self::getUserId() == $user->getId())
		{
			$this->setArchived(1);
			$this->setDataChanged(1);
			$this->deleteThumbs();
			$this->update();
			$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/ad/archive/success']);");
		}
	}
	function unArchive()
	{
		global $katana;
		global $user;
		if(self::getUserId() == $user->getId())
		{
			$this->setArchived(0);
			$this->setDataChanged(1);
			$this->update();
			$katana->addAnalyticsTrack("_gaq.push(['_trackPageview', '/ad/unarchive/success']);");
		}
	}
	
	function update()
	{ self::updateAd(); }
	
	function updateAd()
	{
		if((self::getId() > 0) && (self::getDataChanged()))
		{
			global $user;
			if(($user->getId() == self::getUserId()) || ($user->getLevel() > 4) || (defined('RUN_IMPORT') || defined('RUN_CRON'))) 
			{
				$sql  = 'UPDATE '.DB_PERFIX.self::getDataTable().' SET ';
				$sql .= '`typeId`='.self::getTypeId().', ';
				$sql .= '`catId`='.self::getCatId().', ';
				$sql .= '`brandId`='.self::getBrandId().', ';
				$sql .= '`ModId`='.self::getModId().', ';
				$sql .= '`userId`='.self::getUserId().', ';
				$sql .= '`orderId`='.self::getOrderId().', ';
				$sql .= '`productId`='.self::getProductId().', ';
				
				$sql .= '`isBuying`='.self::getIsBuying().', ';
				$sql .= '`isRent`='.self::getIsRent().', ';
				$sql .= '`isNew`='.self::getIsNew().', ';
				$sql .= '`isCompleted`='.self::getIsCompleted().', ';
				$sql .= '`isValid`='.self::getIsValid().', ';
				
				$sql .= '`title`="'.self::formatText(self::getTitle()).'", ';
				$sql .= '`titleEn`="'.self::formatText(self::getTitleEn()).'", ';
				$sql .= '`description`="'.self::formatText(self::getDescription()).'", ';
				$sql .= '`descriptionEn`="'.self::formatText(self::getDescriptionEn()).'", ';
				$sql .= '`ProductLink`="'.self::formatRemoteUrl(self::getProductLink()).'", ';
				$sql .= '`ProductLink2`="'.self::formatRemoteUrl(self::getProductLink2()).'", ';
				$sql .= '`ProductLinkTxt`="'.self::formatText(self::getProductLinkTxt()).'", ';
				$sql .= '`ProductLinkTxt2`="'.self::formatText(self::getProductLinkTxt2()).'", ';
	
				$sql .= '`priceDisplay`='.self::getPriceDisplay().', ';
				$sql .= '`priceCurrency`="'.self::getPriceCurrency().'", ';
				$sql .= '`priceLocal`=\''.self::getPriceLocal() .'\', ';
				$sql .= '`priceGlobal`=\''.self::getPriceGlobal().'\', ';
				
				$sql .= '`year`='.self::getYear().', ';
				$sql .= '`model`="'.self::getModel().'", ';
				$sql .= '`lengthUsed`='.self::getLengthUsed().', ';
				$sql .= '`weight`='.self::getWeight().', ';
				$sql .= '`power`='.self::getPower().', ';
				$sql .= '`volume`='.self::getVolume().', ';
				$sql .= '`serialNo`="'.self::formatText(self::getSerialNo()).'", ';
				
				$sql .= '`image`="'.self::formatText(self::getImageId()).'", ';
				
				$sql .= '`contactEmail`="'.self::formatText(self::getContactEmail()).'", ';
				$sql .= '`contactName`="'.self::formatText(self::getContactName()).'", ';
				$sql .= '`contactCompany`="'.self::formatText(self::getContactCompany()).'", ';
				$sql .= '`contactWeb`="'.self::formatText(self::getContactWeb()).'", ';
				$sql .= '`contactMob`="'.self::formatText(self::getContactMob()).'", ';
				$sql .= '`contactPhone`="'.self::formatText(self::getContactPhone()).'", ';
				$sql .= '`locationAddress`="'.self::formatText(self::getLocationAddress()).'", ';
				$sql .= '`locationZip`="'.self::formatText(self::getLocationZip()).'", ';
				$sql .= '`locationCity`="'.self::formatText(self::getLocationCity()).'", ';
				$sql .= '`locationCountry`="'.self::formatText(self::getLocationCountry()).'", ';
				$sql .= '`locationCoords`="'.self::formatText(self::getLocationCoords()).'", ';
				$sql .= '`searchKeys`="'.self::formatText(self::getSearchKeys()).'", ';
				$sql .= '`priority`='.self::getPriority().', ';

				//if(self::getDateModified() != '0000-00-00 00:00:00')
				//{ $sql .= '`dateModified`="'.self::getDateModified().'", '; } 
				//else
				//{
					if(!defined('RUN_IMPORT')) // If date modified not set and not running import then set it to now.
					{ $sql .= '`dateModified`=NOW(), '; }
				//}
				
				$sql .= '`datePaid`="'.self::getDatePaid().'", ';
				if(self::getDateCreated() != '0000-00-00 00:00:00')
				{ $sql .= '`dateCreated`="'.self::getDateCreated().'", '; }
				$sql .= '`dateActiveStart`="'.self::getDateActiveStart().'", ';
				$sql .= '`dateActiveEnd`="'.self::getDateActiveEnd().'", ';
				
				$sql .= '`GalleryDisplay`='.self::getGalleryDisplay().', ';
				$sql .= '`ViewsGallery`='.self::getViewsGallery().', ';
				$sql .= '`RemoteId`='.self::getRemoteId().', ';
				$sql .= "`RemoteUrl`='".self::getRemoteUrl()."', ";
				$sql .= '`AdQuotas`='.self::getAdQuotas().', ';
				
				$sql .= '`active`='.intval(self::getActive()).', ';
				$sql .= '`archived`='.self::getArchived().', ';
				$sql .= '`deleted`='.self::getDeleted().' ';
				
				$sql .= ' WHERE id='.self::getId().' LIMIT 1;';

				//if(($user->getId() == 1) || (defined('RUN_IMPORT')))
				//{ echo $sql.'<br /><hr />'; } 
				mysql_query($sql);
			}
		}
	}
	
	function insert()
	{
		global $adc;
		global $user;
		$id = 0;
		if((self::getUserId() > 0) && (self::getTypeId() > 0) && (self::getCatId() > 0))
		{
			$insert = '`typeId`';
			$values = ''.self::getTypeId();
			
			$insert .= ', `catId`';
			$values .= ', '.self::getCatId();
			
			$insert .= ', `brandId`';
			$values .= ', '.self::getBrandId();
			
			$insert .= ', `userId`';
			$values .= ', '.self::getUserId();
			
			$insert .= ', `RemoteId`';
			$values .= ', '.self::getRemoteId();
			
			if(self::getTitle() != '')
			{
				$insert .= ', `title`';
				$values .= ', "'.self::getTitle().'"';
			}
			if(self::getTitleEn() != '')
			{
				$insert .= ', `titleEn`';
				$values .= ', "'.self::getTitleEn().'"';
			}
			if(self::getModel() != '')
			{
				$insert .= ', `model`';
				$values .= ', "'.self::getModel().'"';
			}
			if(self::getYear() > 0)
			{
				$insert .= ', `year`';
				$values .= ', '.self::getYear();
			}
			if(self::getLengthUsed() > 0)
			{
				$insert .= ', `lengthUsed`';
				$values .= ', '.self::getLengthUsed();
			}
			
			if(self::getProductId() > 0)
			{
				if((self::getUseCredits() > 0) && ($user->getCreditsLeft() > 0) && (self::getGalleryDisplay() == 0))
				{
					self::setAdQuotas(-1);
					$creditsUsed = 0;
					$creditsUsed = ($user->getCreditsUsed() + 1);
					$user->setCreditsUsed($creditsUsed);
					$user->saveUser();
					$insert .= ', `AdQuotas`';
					$values .= ', -1';
				}
				else
				{
					$insert .= ', `productId`';
					$values .= ', '.$productId;
					
					$insert .= ', `AdQuotas`';
					$values .= ', '.self::getAdQuotas();
				}
			}
			else
			{
				$insert .= ', `datePaid`';
				$values .= ', NOW()';
			}
			
			$insert .= ', `isBuying`';
			$values .= ', '.self::getIsBuying();
			
			$insert .= ', `isRent`';
			$values .= ', '.self::getIsRent();
			
			$insert .= ', `isNew`';
			$values .= ', '.self::getIsNew();
			
			$insert .= ', `GalleryDisplay`';
			$values .= ', '.self::getGalleryDisplay();
			
			if(self::getDescription() != '')
			{
				$insert .= ', `description`';
				$values .= ', "'.self::getDescription().'"';
			}
			
			if(self::getDescriptionEn() != '')
			{
				$insert .= ', `descriptionEn`';
				$values .= ', "'.self::getDescriptionEn().'"';
			}
			
			
			$insert .= ', `dateCreated`';
			$values .= ', NOW()';
			
			$insert .= ', `dateModified`';
			$values .= ', NOW()';
			
			$sql  = 'INSERT INTO '.DB_PERFIX.'am_ads ('.$insert.') '; 
			$sql .= 'VALUES ('.$values.');';
			$result = mysql_query($sql);
			//if(($user->getId() == 1) || (defined('RUN_IMPORT')))
			//{ echo $sql; }
			
			$sql  = 'SELECT id FROM '.DB_PERFIX.'am_ads WHERE `userId`='.self::getUserId().' AND ';
			$sql .= '`typeId`='.self::getTypeId().' AND ';
			$sql .= '`catId`='.self::getCatId().' AND ';
			$sql .= '`active`=0 AND ';
			$sql .= '`dateCreated` > "'.date('Y-m-d h:').' 00:00" ';
			$sql .= 'ORDER BY id DESC LIMIT 1;';
			$result = mysql_query($sql);
			
			//if(($user->getId() == 1) || (defined('RUN_IMPORT')))
			//{ echo $sql; }
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{ 
					self::setId($row['id']); 
					$id = $row['id'];
				}
			}
			$adc->setTTL(0);
		}
		return $id;
	}
	
	function updateCoords()
	{
		if((self::getId() > 0) && (self::getDataChanged()))
		{
			$sql  = 'UPDATE '.DB_PERFIX.self::getDataTable().' SET ';
			$sql .= '`locationCoords`="'.self::formatText(self::getLocationCoords()).'", ';
			$sql .= '`deleted`='.self::getDeleted().' ';
			$sql .= ' WHERE id='.self::getId().' LIMIT 1;';
			mysql_query($sql);
		}
	}
	
	public function loadImages()
	{
		if((self::getId() > 0) && (self::getItemLoaded('images') == 0))
		{
			global $db;
			global $adc;
			
			$sql = 'SELECT * FROM '.DB_PERFIX.self::getImagesTable().' WHERE adId='.self::getId().' ORDER BY `imageOrder` ASC;';
			$result = $db->query($sql);
			$data 	= $db->fetch($sql, $adc->getTTL());
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Images[$row['id']] = new Image($row);
					$this->Images[$row['id']]->setDataTable(self::getImagesTable());
					$this->Images[$row['id']]->setParentIdField('adId');
					$this->Images[$row['id']]->setParentId(self::getId());
					$this->Images[$row['id']]->setFolderPath(ADS_PATH);
					$this->Images[$row['id']]->setFolderUrl(ADS_URL);
					if($this->Images[$row['id']]->getImageOrder() == 0)
					{ 
						self::setImage($this->Images[$row['id']]); 
						self::setImageId($row['id']);
					}
				}
			}
			self::setItemLoaded('image', 1);
			self::setItemLoaded('images', 1);
		}
	}
	
	function uploadImage($file)
	{
		global $thumb;
		global $db;
		
		$order = 0;
		$sql = 'SELECT id, imageOrder FROM '.DB_PERFIX.self::getImagesTable().' WHERE adId='.self::getId().' ORDER BY imageOrder DESC LIMIT 1;';
		$result = mysql_query($sql);
		if(mysql_num_rows($result) > 0)
		{ 
			while($row = mysql_fetch_array($result))
			{
				if($row['id'] > 0)
				{ $order = $row['imageOrder'] + 1; }
			}
		}
		
		$image = self::uploadObjectImage(ADS_PATH, $file, $thumb['ADS'], self::getId().date('Ymdhis').'_'.$order.'_'.rand(10000,90000));
		
		if(is_file(ADS_PATH.$image))
		{
			$sql = 'INSERT INTO '.DB_PERFIX.self::getImagesTable().' (`id`, `adId`, `filename`, `imageOrder`) ';
			$sql .= ' VALUES (NULL, '.self::getId().', "'.$image.'", '.$order.');';
			$result = mysql_query($sql);
			self::setItemLoaded('image', 0);
			self::setItemLoaded('images', 0);
			self::loadImages();
			return $result;
		}
	}
	
	function deleteImage($id = 0)
	{
		if($id > 0)
		{
			$images = self::getImages();
			if(is_object($images[$id]))
			{
				global $thumb;
				self::deleteObjectImage(ADS_PATH, $images[$id]->getFilename(), $thumb['ADS']);

				$sql = 'DELETE FROM '.DB_PERFIX.self::getImagesTable().' WHERE id='.intval($id).' LIMIT 1;';
				$result = mysql_query($sql);
				
				unset($this->Image);
				unset($this->Images[$id]);
				
				self::setItemLoaded('image', 0);
				self::setItemLoaded('images', 0);
				self::loadImages();
			
				if(count($this->Images) > 0)
				{ self::reorderImages(); }
				
				return;
			}
		}
	}
	
	function deleteImages()
	{
		$images = self::getImages();
		
		if(count($images) > 0)
		{
			global $thumb;
			foreach($images as $image)
			{
				self::deleteObjectImage(ADS_PATH, $image->getFilename(), $thumb['ADS']);
				$sql = 'DELETE FROM '.DB_PERFIX.self::getImagesTable().' WHERE id='.$image->getId().' LIMIT 1;';
				$result = mysql_query($sql);
			}
			
			self::setItemLoaded('image', 0);
			self::setItemLoaded('images', 0);
			return count($images);
		}
	}
	
	function deleteThumbs()
	{
		$images = self::getImages();
		if(count($images) > 0)
		{
			global $thumb;
			foreach($images as $image)
			{ self::deleteObjectThumbs(ADS_PATH, $image->getFilename(), $thumb['ADS']); }
		}
	}
	
	function reorderImages()
	{
		self::loadImages();
		if(count($this->Images) > 0)
		{
			$imageOrder = 0;
			foreach($this->Images as $img)
			{
				if($imageOrder == 0)
				{ 
					self::setImage($img->getId());
					self::updateAd();
				}
				$img->setImageOrder($imageOrder);
				$img->setDataChanged(1);
				$img->update();
				$imageOrder++;
			}
			self::setItemLoaded('image', 0);
			self::setItemLoaded('images', 0);
			self::loadImages();
		}
	}
	
	function rotateImage($id = 0, $direction='cw')
	{
		if($id > 0)
		{
			$images = self::getImages();
			if(is_object($images[$id]))
			{
				global $thumb;
				$filename = self::rotateObjectImage(ADS_PATH, $images[$id]->getFilename(), $thumb['ADS'], $direction, self::getId().date('Ymdhis'));
				if(is_file(ADS_PATH.$filename))
				{
					$images[$id]->setFilename($filename);
					$images[$id]->setDataChanged(1);
					$images[$id]->update();
					self::setItemLoaded('image', 0);
					self::setItemLoaded('images', 0);
					self::loadImages();
				}
				return;
			}
		}
	}
	
	public function loadFiles()
	{
		if((self::getId() > 0) && (self::getItemLoaded('Files') == 0))
		{
			global $db;
			global $adc;
			
			$sql = 'SELECT * FROM '.DB_PERFIX.self::getFilesTable().' WHERE adId='.self::getId().' ORDER BY `FileOrder` ASC;';
			$result = $db->query($sql);
			$data 	= $db->fetch($sql, $adc->getTTL());
			
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Files[$row['Id']] = new File($row);
					$this->Files[$row['Id']]->setDataTable(self::getFilesTable());
					$this->Files[$row['Id']]->setParentIdField('AdId');
					$this->Files[$row['Id']]->setParentId(self::getId());
					$this->Files[$row['Id']]->setFolderPath(ADFILE_PATH);
					$this->Files[$row['Id']]->setFolderUrl(ADFILE_URL);
				}
			}
			self::setItemLoaded('Files', 1);
		}
	}
	
	function uploadFile($file)
	{
		global $db;
		
		$order = 0;
		$sql = 'SELECT Id, FileOrder FROM '.DB_PERFIX.self::getFilesTable().' WHERE AdId='.self::getId().' ORDER BY FileOrder DESC LIMIT 1;';
		$result = mysql_query($sql);
		if(mysql_num_rows($result) > 0)
		{ 
			while($row = mysql_fetch_array($result))
			{
				if($row['id'] > 0)
				{ $order = $row['FileOrder'] + 1; }
			}
		}
		
		$filename = $file['name'];
		$file = self::uploadObjectFile(ADFILE_PATH, $file, self::getId().date('Ymdhis').'_'.$order.'_'.rand(10000,90000));
		
		if(is_file(ADFILE_PATH.$file))
		{
			$sql = 'INSERT INTO '.DB_PERFIX.self::getFilesTable().' (`Id`, `AdId`, `Title`, `Filename`, `FileOrder`) ';
			$sql .= ' VALUES (NULL, '.self::getId().', "'.self::formatText($filename).'", "'.$file.'", '.$order.');';
			$result = mysql_query($sql);
			self::setItemLoaded('Files', 0);
			self::loadFiles();
			return $result;
		}
	}
	
	function deleteFile($id = 0)
	{
		if($id > 0)
		{
			$files = self::getFiles();
			if(is_object($files[$id]))
			{
				global $thumb;
				self::deleteObjectFile(ADFILE_PATH, $files[$id]->getFilename());

				$sql = 'DELETE FROM '.DB_PERFIX.self::getFilesTable().' WHERE id='.intval($id).' LIMIT 1;';
				$result = mysql_query($sql);
				
				unset($this->Files[$id]);
				
				self::setItemLoaded('files', 0);
				self::loadFiles();
			
				if(count($this->Files) > 0)
				{ self::reorderFiles(); }
				
				return;
			}
		}
	}
	
	function reorderFiles()
	{
		self::loadFiles();
		if(count($this->Files) > 0)
		{
			$fileOrder = 0;
			foreach($this->Files as $img)
			{
				if($fileOrder == 0)
				{ 
					self::setFile($img->getId());
					self::updateAd();
				}
				$img->setFileOrder($fileOrder);
				$img->setDataChanged(1);
				$img->update();
				$fileOrder++;
			}
			self::setItemLoaded('files', 0);
			self::loadFiles();
		}
	}
}
?>